<script setup>
import HeaderMenuWhite from "~/components/base/HeaderMenuWhite.vue";
import { Picture } from "@element-plus/icons-vue";
import { ref, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import QRCode from "qrcode.vue";
import { getQRCodeUrl, checkQRCodeStatus } from "~/api/user";
import { ElMessage } from "element-plus";

const formData = ref({});
const router = useRouter();
const qrValue = ref("");
const qrSize = ref(200);
const qrCodeId = ref("");
const loading = ref(false);
let checkTimeoutId = null;
let debounceTimer = null;

const back = () => {
  router.back();
};

// 防抖函数
const debounce = (fn, delay = 500) => {
  return (...args) => {
    if (debounceTimer) {
      clearTimeout(debounceTimer);
    }
    debounceTimer = setTimeout(() => {
      fn(...args);
    }, delay);
  };
};

// 实际获取二维码的函数
const fetchQRCode = async () => {
  if (loading.value) {
    return;
  }

  if (!formData.value.name || !formData.value.certNo) {
    ElMessage.warning("请填写姓名和身份证号码");
    return;
  }
  
  // 正则验证身份证号码
  const certNoReg =
    /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\d{3}[\dXx]$/;
  if (!certNoReg.test(formData.value.certNo)) {
    ElMessage.warning("请填写正确的身份证号码");
    return;
  }
  
  try {
    loading.value = true;
    const params = {
      certName: formData.value.name,
      certNo: formData.value.certNo,
    };
    const response = await getQRCodeUrl(params);
    
    // 检查响应状态
    if (response.code === 200 && response.data) {
      qrValue.value = response.data.url;
      qrCodeId.value = response.data.certifyId;
      startChecking();
      ElMessage.success("二维码生成成功");
    } else {
      // 显示后端返回的具体错误信息
      ElMessage.error(response.msg || "获取二维码失败");
    }
  } catch (error) {
    console.error("获取二维码失败:", error);
    // 网络错误或其他异常才显示通用提示
    // 后端业务错误已经在上面的 else 中处理了
  } finally {
    loading.value = false;
  }
};

// 使用防抖的二维码获取函数
const getQRCode = debounce(fetchQRCode, 500);

const startChecking = () => {
  if (checkTimeoutId) {
    clearTimeout(checkTimeoutId);
  }
  checkStatus();
};

const checkStatus = async () => {
  try {
    const response = await checkQRCodeStatus({ certifyId: qrCodeId.value });
    if (response.data && response.data.result === 1) {
      // 处理验证成功的逻辑，例如显示成功消息或跳转页面
      router.push("/createEnd");
    } else {
      // 如果验证未成功,设置下一次检查
      checkTimeoutId = setTimeout(checkStatus, 3000);
    }
  } catch (error) {
    console.error("检查二维码状态失败:", error);
    // 即使发生错误,也设置下一次检查
    checkTimeoutId = setTimeout(checkStatus, 3000);
  }
};

const reloadQR = () => {
  // 清除之前的定时器
  if (checkTimeoutId) {
    clearTimeout(checkTimeoutId);
  }
  // 重新获取二维码
  getQRCode();
};

onUnmounted(() => {
  if (checkTimeoutId) {
    clearTimeout(checkTimeoutId);
  }
  if (debounceTimer) {
    clearTimeout(debounceTimer);
  }
});
</script>

<template>
  <div class="real-name">
    <HeaderMenuWhite :bgColor="'white'" :showSearch="false" />
    <div class="form-items">
      <div class="item">
        <h4 class="title">
          <span></span> 专业技能
          <i>请如实填写你的个人信息，技能猴子承诺保障用户的信息安全</i>
        </h4>
        <el-form
          :model="formData"
          label-position="top"
          style="margin-top: 30px"
        >
          <el-form-item label="姓名">
            <el-input
              v-model="formData.name"
              placeholder="请填写真实姓名（不对外展示）"
              style="width: 100%"
            ></el-input>
          </el-form-item>
          <el-form-item label="身份证号码">
            <el-input
              v-model="formData.certNo"
              placeholder="请填写身份证件号码"
              style="width: 100%"
            ></el-input>
          </el-form-item>
          <el-form-item label="生成验证码" v-if="!qrValue">
            <el-button 
              class="generate-code" 
              type="primary" 
              :loading="loading"
              :disabled="loading"
              @click="getQRCode"
            >
              {{ loading ? '生成中...' : '生成验证码' }}
            </el-button>
          </el-form-item>
          <el-form-item label="支付宝扫码认证" v-if="qrValue">
            <div class="qr-code">
              <div class="qr-code-img">
                <QRCode :value="qrValue" :size="qrSize" />
              </div>
              <p 
                class="re-load-qr" 
                :class="{ 'loading': loading }"
                @click="reloadQR"
              >
                <span class="reload-icon">↻</span> 
                {{ loading ? '加载中...' : '重新加载二维码' }}
              </p>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="btns">
      <el-button class="close" @click="back">上一步</el-button>
    </div>
  </div>
</template>

<style scoped lang="scss">
.real-name {
  background: #f9f9f9;
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.form-items {
  flex: 1;
  overflow-y: auto;
  padding-top: 80px;
  
  @media (max-width: 768px) {
    padding-top: 60px;
  }
  
  @media (max-width: 480px) {
    padding-top: 56px;
  }
  
  .item {
    width: 1200px;
    margin: 32px auto 0;
    background: #ffffff;
    border-radius: 16px 16px 16px 16px;
    border: 1px solid rgba(25, 30, 40, 0.08);
    padding: 20px 20px 30px;
    
    @media (max-width: 1240px) {
      width: calc(100% - 40px);
      margin: 32px 20px 0;
    }
    
    @media (max-width: 768px) {
      margin: 20px 16px 0;
      padding: 16px;
    }
    
    @media (max-width: 480px) {
      margin: 16px 12px 0;
      padding: 12px;
    }
  }
  .title {
    display: flex;
    align-items: center;
    font-size: 16px;
    margin-bottom: 20px;
    span {
      width: 2px;
      height: 12px;
      background: #1dbf73;
      border-radius: 10px 10px 10px 10px;
      margin-right: 6px;
    }
    i {
      font-style: normal;
      font-size: 12px;
      color: #008571;
      margin-left: 8px;
    }
  }
}
.qr-code {
  width: 220px;
  height: 240px; // 增加高度以容纳重新加载文本
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.qr-code-img {
  border: 1px solid rgba(25, 30, 40, 0.08);
  width: 220px;
  height: 220px; // 增加高度以容纳重新加载文本
  padding: 10px;
  box-sizing: border-box;
  border-radius: 6px;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #fff;
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
.re-load-qr {
  display: flex;
  align-items: center;
  color: #1dbf73;
  cursor: pointer;
  justify-content: center;
  line-height: 14px;
  margin-top: 10px;
  user-select: none;
  
  &.loading {
    opacity: 0.6;
    cursor: not-allowed;
  }
  
  .reload-icon {
    font-size: 18px;
    margin-right: 4px;
    display: inline-block;
    transform: rotate(0deg);
    transition: transform 0.3s ease;
  }
  &:hover:not(.loading) .reload-icon {
    transform: rotate(180deg);
  }
}
.generate-code {
  background: #1dbf73;
  border-radius: 8px 8px 8px 8px;
  color: #fff;
  border: none;
}
.btns {
  display: flex;
  height: 80px;
  align-items: center;
  justify-content: center;
  background: #fff;
  .close {
    width: 92px;
    height: 36px;
    background: #ffffff;
    border-radius: 8px 8px 8px 8px;
    border: 1px solid rgba(25, 30, 40, 0.08);
    color: rgba(25, 30, 40, 0.6);
  }
  .next {
    width: 92px;
    height: 36px;
    background: #1dbf73;
    border-radius: 8px 8px 8px 8px;
    color: #fff;
  }
}
</style>

<style>
.real-name .el-form-item--label-top .el-form-item__label {
  color: #191e28;
  font-weight: 400;
}
.real-name .el-input__wrapper {
  height: 48px;
  border-radius: 8px 8px 8px 8px;
  border: 1px solid rgba(25, 30, 40, 0.08);
  box-shadow: none;
}
.el-image {
  width: 100%;
  height: 100%;
}
</style>
